class Edit < ActiveRecord::Base
  #Relations
  belongs_to :editable, :polymorphic => true
  belongs_to :user, :counter_cache => true

  #used to maintain the hash when reviewing
  # the edit later
  serialize :change

  #Checks if this edit is for a delete
  # if so, return true, otherwise false
  def is_delete?
    if self.change.key?('delete')
      return true
    else
      return false
    end
  end 

  #Creates an edit entry with the provided HASH
  # of changes, and the item provided.
 def self.create_edit(changes, item)
   edit = Edit.new

   # Get current user
   current_user_session = UserSession.find
   current_user = current_user_session.record
   edit.user_id = current_user.id

   #Get a nicer looking hash of changes
   edit.change = clean_hash(changes)

   #Set the polymorphic association
   edit.editable = item

   #Simple edit, auto approved
   edit.approved = true
   edit.moderated = true

   #Save the edit
   edit.save!
 end
 
 #Makes the changes hash a little more
 # readable
 def self.clean_hash(changes)
      edit_changes = Hash.new

    #Loop through each changed value and
    # improve the readablity of the output
    # and replaces id keys with name values
    changes.each do |key, value|
      new_key = key
      new_value = value

      if key == "city_id"
        old_city = City.find(value.first) unless value.first.nil?
        new_city = City.find(value.last) unless value.last.nil?
        new_key = "city"
        new_value =  [old_city.to_s, new_city.to_s]

      elsif key == "country_id"
        old_country = Country.find(value.first) unless value.first.nil?
        new_country = Country.find(value.last) unless value.last.nil?
        new_key = "country"
        new_value = [old_country.to_s, new_country.to_s]

      elsif key == "label_id"
        puts value
        old_label = Label.find(value.first) unless value.first.nil?
        new_label = Label.find(value.last) unless value.last.nil?
        new_key = "label"
        new_value = [old_label.to_s, new_label.to_s]

      elsif key == "formdate_day"
        new_key = "begin day"
      elsif key == "formdate_month"
        new_key = "begin month"
      elsif key == "formdate_year"
        new_key = "begin year"
      elsif key == "breakdate_day"
        new_key = "end day"
      elsif key == "breakdate_month"
        new_key = "end month"
      elsif key == "breakdate_year"
        new_key = "end year"
      elsif key == "proper_name"
        new_key = "birth name"
      end

      edit_changes.store(new_key, new_value)
    end

    edit_changes.delete("created_at")
    edit_changes.delete("updated_at")
    return edit_changes
  end

end
